// 判断客户端是否iphone
export const isIPhone = () => {
  return window.navigator.appVersion.match(/iphone/gi)
}

// 判断客户端是否android
export const isAndroid = () => {
  return window.navigator.appVersion.match(/android/gi)
}

/**
 * 浏览器是否支持LocalStroage
 * @returns {*}
 */
function getLocalStroage () {
  if (!window.localStorage) {
    console.warn('浏览器不支持LocalStroage!')
    return
  }
  return window.localStorage
}

/**
 * LocalStroage是否存在key
 * @param key
 * @returns {boolean}
 */
function isExist (key) {
  var ls = getLocalStroage()
  return ls && ls.length === 0 ? false : ls.getItem(key) !== null
}

/**
 * 操作localstorage
 * @type {{set: localStorage.set, get: localStorage.get, remove: localStorage.remove}}
 */
export const localStorage = {
  set: function (key, value) {
    if (arguments.length === 1 && Object.prototype.toString.call(key).slice(8, -1) === 'Object') {
      for (var name in key) {
        if (Object.prototype.toString.call(key[name]).slice(8, -1) === 'Object') key[name] = JSON.stringify(key[name])
        getLocalStroage().setItem(name, key[name])
      }
    } else {
      if (Object.prototype.toString.call(value).slice(8, -1) === 'Object') value = JSON.stringify(value)
      getLocalStroage().setItem(key, value)
    }
    return this
  },
  get: function (key) {
    if (isExist(key)) {
      var value = getLocalStroage().getItem(key)
      try {
        return JSON.parse(value) || null
      } catch (e) {
        return value || null
      }
    }
  },
  remove: function (key) {
    if (isExist(key)) {
      getLocalStroage().removeItem(key)
    }
    return this
  }
}

export const COLOR = ['#47B8FE', '#FBB32B', '#7ED1A5', '#FB488A', '#A69AE4',
  '#FA9677', '#BCD932', '#f5ff51',
  '#07a2a4', '#9a7fd1', '#588dd5', '#f5994e', '#c05050',
  '#59678c', '#c9ab00', '#7eb00a', '#6f5553', '#c14089']

export function extend () {
  let options
  let name
  let src
  let copy
  let copyIsArray
  let clone
  let target = arguments[0] || {}
  let i = 1
  let length = arguments.length
  let deep = false

  if (typeof target === 'boolean') {
    deep = target
    target = arguments[i] || {}
    i++
  }

  if (typeof target !== 'object' && !isFunction(target)) {
    target = {}
  }

  if (i === length) {
    target = this
    i--
  }

  for (; i < length; i++) {
    if ((options = arguments[i]) != null) {
      for (name in options) {
        src = target[name]
        copy = options[name]

        if (target === copy) {
          continue
        }

        if (deep && copy && (isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
          if (copyIsArray) {
            copyIsArray = false
            clone = src && Array.isArray(src) ? src : []
          } else {
            clone = src && isPlainObject(src) ? src : {}
          }
          target[name] = extend(deep, clone, copy)
        } else if (copy !== undefined) {
          target[name] = copy
        }
      }
    }
  }

  return target
}

function isPlainObject (obj) {
  let proto, Ctor

  if (!obj || toString.call(obj) !== '[object Object]') {
    return false
  }

  proto = getProto(obj)

  if (!proto) {
    return true
  }

  Ctor = hasOwn.call(proto, 'constructor') && proto.constructor
  return typeof Ctor === 'function' && fnToString.call(Ctor) === ObjectFunctionString
}

export function isFunction (obj) {
  return typeof obj === 'function' && typeof obj.nodeType !== 'number'
}

function hasOwn () {
  return {}.hasOwnProperty
}

const fnToString = hasOwn.toString

const ObjectFunctionString = fnToString.call(Object)

const getProto = Object.getPrototypeOf

/**
 * 判断是否为整数
 * @param obj
 * @return {boolean}
 */
export function isInteger (obj) {
  return Math.floor(obj) === obj
}

/**
 * 判断是否为数字
 * @param num
 * @return {boolean}
 */
export function isNumber (num) {
  let number = +num

  if ((number - number) !== 0) {
    // Discard Infinity and NaN
    return false
  }

  if (number === num) {
    return true
  }

  if (typeof num === 'string') {
    // String parsed, both a non-empty whitespace string and an empty string
    // will have been coerced to 0. If 0 trim the string and see if its empty.
    if (number === 0 && num.trim() === '') {
      return false
    }
    return true
  }
  return false
}

/**
 * 保留两位小数
 * @param num
 * @param isRate 是否为率
 * @param decimal 保留几位小数
 * @return {*}
 */
export function parseNum (num, isRate, decimal) {
  decimal = decimal || 2
  if (isNumber(num)) {
    if (isInteger(num)) {
      if (isRate) {
        return (parseFloat(num) * 100).toFixed(decimal) + '%'
      } else {
        return num
      }
    } else {
      if (isRate) {
        return (parseFloat(num) * 100).toFixed(decimal) + '%'
      } else {
        return parseFloat(num).toFixed(decimal)
      }
    }
  } else {
    // 1/0
    if (num === Infinity || num === null) {
      return '--'
    }
    return num
  }
}

/**
 * 当年总天数
 * @param year
 * @return {number}
 */
export function getYearDays (year) {
  if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
    return 366
  }
  return 365
}

/**
 * 获取当前月份的天数, 返回当月天数，例如: getMonthDays(2018, 5) 获取的是2018年5月的总天数;
 * @param year
 * @param month
 * @return {number}
 */
export function getMonthDays (year, month) {
  var days = new Date(year, month, 0)
  return days.getDate()
}

export function sortByKey (list, key, asc) {
  list = list.slice(0)
  asc = asc || false
  return asc ? list.sort(compare(key)).reverse() : list.sort(compare(key))
}

function compare (property) {
  return function (a, b) {
    var value1 = a[property]
    var value2 = b[property]
    var result = 0
    // 百分数计算
    if ((typeof value1 === 'string' && value1.indexOf('%') > -1) || (typeof value2 === 'string' && value2.indexOf('%') > -1)) {
      result = parseFloat(value2) - parseFloat(value1)
    } else {
      result = value2 > value1 ? 1 : value2 < value1 ? -1 : 0
    }
    return result
  }
}

/**
 * 舆情列表获取对应module
 * @param  {[type]} currentDimension [description]
 * @return {[type]}                  [description]
 */
export function getModule (currentDimension) {
  let module
  if (currentDimension === '房企动态') {
    module = '房企动态'
  } else if (currentDimension === '人物言论') {
    module = '人物言论'
  } else if (currentDimension === '宏观资讯') {
    module = '宏观资讯区域要闻'
  } else if (currentDimension === '区域要闻') {
    module = '宏观资讯区域要闻'
  } else {
    module = ''
  }
  return module
}

export function getTime (startTime, endTime, isLong) {
  let start = ''
  let end = ''
  if (isLong) {
    start = new Date(startTime).format('yyyy-MM-dd') + ' 00:00:00'
    end = new Date(endTime).format('yyyy-MM-dd') + ' 23:59:59'
    if (isIPhone()) {
      start = start.replace(/\-/g, '/')
      end = end.replace(/\-/g, '/')
    }
    start = new Date(start).getTime()
    end = new Date(end).getTime()
  } else {
    start = new Date(startTime).format('yyyy-MM-dd') + ' 00:00:00'
    end = new Date(endTime).format('yyyy-MM-dd') + ' 23:59:59'
  }
  return {
    startTime: start,
    endTime: end
  }
}
